package com.gem.day14.homework;

import java.io.*;
import java.text.DecimalFormat;

public class IOUtils {

	//拆分文件
	public static void split(String file, int size) {
		try {
			InputStream in = new FileInputStream(file);
			int index = 0;
			DecimalFormat fmt = new DecimalFormat("000");
			String ext = fmt.format(index++);
			String filename = file + "." + ext;
			OutputStream out = new FileOutputStream(filename);
			byte[] buf = new byte[1024];
			int count;
			int n = 0;
			while ((count = in.read(buf)) != -1) {
				out.write(buf, 0, count);
				n++;
				if (n % size == 0) {
					out.close();
					ext = fmt.format(index++);
					filename = file + "." + ext;
					out = new FileOutputStream(filename);
				}
			}
			out.close();
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	//合并文件
	public static void join(String file) {
		try {
			int dot = file.lastIndexOf(".");
			String outFile = file.substring(0, dot);
			int index = 0;
			DecimalFormat fmt = new DecimalFormat("000");
			String ext = fmt.format(index++);
			String inFile = outFile + "." + ext;
			InputStream in = new FileInputStream(inFile);
			OutputStream out = new FileOutputStream(outFile);
			int count;
			byte[] buf = new byte[1024];
			while (true) {
				while ((count = in.read(buf)) != -1) {
					out.write(buf, 0, count);
				}
				in.close();
				ext = fmt.format(index++);
				inFile = outFile + "." + ext;
				File f = new File(inFile);
				if (!f.exists()) {
					break;
				}
				in = new FileInputStream(inFile);
			}
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
}
